<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>即时通讯系统</title>
</head>
<body>
    <div id="convo">
        登录用户id：<input type="text" name="user">
        <button class="login">登录</button>
        <ul class="chat-thread">
        </ul>
        <!--聊天框-->
        <div class="chat-window">
            <input class="chat-window-message" name="chat-window-message" autocomplete="on" placeholder="请输入内容按回车键发送"
                type="text" value="123">
        </div>
    </div>
    <!--引入jq文件-->
    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    <script type="text/javascript">
        $('.login').on('click', function () {
            uid = $('[name=user]').val().trim();
            if (uid == '') {
                alert('请先登录');
            } else {
                socketlogin(uid);
            }
        })
        var socket;
        function socketlogin(uid) {
            socket = new WebSocket('ws://127.0.0.1:9503?uid=' + uid);
            socket.onopen = function () {
                socket.send(setMsg(1, '用户' + uid + "你好", uid));
                console.log('连接成功');
            }
            socket.onmessage = function (e) {
                console.log('接收数据');
                console.log(e);
                $('.chat-thread').append('<li class="left">' + e.data + '</li>');
            }
            socket.onclose = function () {
                $('.chat-thread').append('<li class="left">退出聊天室</li>');
            }
        }
        $(document).keydown(function (e) {
            if (e.keyCode == 13) {
                var speak = $('.chat-window-message').val();
                $('.chat-thread').append('<li>' + speak + '</li>');
                $('.chat-window-message').val('');
                socket.send(setMsg(2, speak, uid));
            }
        })

        function setMsg(type, msg, uid) {
            var msgObject = {
                type: type,
                msg: msg,
                uid: uid,
            }
            return JSON.stringify(msgObject);
        }
    </script>